package bch.rocketmq.config;

import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisException;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.spring.transaction.RedissonTransactionManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
public class RedissionConfig {


    @Resource
    RedisProperties redisProperties;


    @Bean()
    public RRateLimiter rateLimiter() {
        RRateLimiter rateLimiter = redissonClient().getRateLimiter("sk2-rateLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.SECONDS);
        return rateLimiter;
    }



    @Bean
    @ConditionalOnProperty(prefix = "spring.data.redis", name = "host")
    public RedissonClient redissonClient() {
        Config config = new Config();
        config
                .setCodec(new StringCodec())
                .useSingleServer()
                .setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setPassword(redisProperties.getPassword())
                .setDatabase(redisProperties.getDatabase());

        return Redisson.create(config);
    }

    @Bean
    public RedissonTransactionManager redissonTransactionManager(RedissonClient redissonClient) {
        RedissonTransactionManager redissonTransactionManager = new RedissonTransactionManager(redissonClient);
        return redissonTransactionManager;
    }

    @Bean
    public JdbcTransactionManager jdbcTransactionManager(DataSource dataSource) {
        return new JdbcTransactionManager(dataSource);
    }

    @Bean
    public ChainedTransactionManager chainedTransactionManager(
            JdbcTransactionManager jdbcTransactionManager,
            RedissonTransactionManager redissonTransactionManager) {
        return new ChainedTransactionManager(jdbcTransactionManager, redissonTransactionManager);
    }


}
